<template>
  <view class="setting-container">
    <navbar title="设置">
      <view slot="left"/>
    </navbar>
    <view class="cell-group">
      <view class="cell">
        <view class="cell-left">
          <text>头像</text>
        </view>
        <view class="cell-right">
          <button hover-class="none" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
            <image :src="form.avatar || defAvatar" mode="aspectFit" class="avatar-img"/>
          </button>
        </view>
      </view>
      <view class="cell" @click="showNicknamePopup = true;focus = false">
        <view class="cell-left">
          <text>昵称</text>
        </view>
        <view class="cell-right">
          <text>{{userInfo.realname}}</text>
          <text class="iconfont icon-arrow_right"/>
        </view>
      </view>
      <view class="cell">
        <view class="cell-left">
          <text>手机号</text>
        </view>
        <view class="cell-right">
          <text v-if="userInfo && userInfo.phone">{{$utils.phoneStar(userInfo.phone)}}</text>
          <template v-else>
            <button class="unphone" open-type="getPhoneNumber" hover-class="none" @getphonenumber="onGetPhoneNumber">绑定手机号</button>
            <text class="iconfont icon-arrow_right"/>
          </template>
        </view>
      </view>
      <view class="cell" @click="toEditPassword">
        <view class="cell-left">
          <text>修改密码</text>
        </view>
        <view class="cell-right">
          <text class="iconfont icon-arrow_right"/>
        </view>
      </view>
      <button class="logout-btn" @click="logoutShow = true">退出登录</button>
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <ws-wx-privacy ref="privacyPopup" id="privacy-popup"/>
    <!-- #endif -->
    <c-popup title="修改昵称" v-model="showNicknamePopup" @confirm="updateNickname">
      <view class="nick-input" @touchstart.stop="handleTouchInput">
        <input type='nickname'
               name='nickname'
               :value="form.realname"
               placeholder="请输入您的昵称"
               placeholder-class="place"
               :focus="focus"
               @change="changeInput"
        >
      </view>
    </c-popup>
    <c-modal v-model="logoutShow" @confirm="handleLogout">确认退出登录吗？</c-modal>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import upload from "@/api/upload";
import {updateUserInfo, updateUserPhone} from "@/api/my";
import {getPhone, getSessionKey, miniLogout, wxLogin} from "@/api/login";
export default {
  data() {
    return {
      defAvatar: require('@/static/images/avatar.png'),
      form: {},
      focus: false,
      showNicknamePopup: false,
      logoutShow: false
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    ...mapActions(['setUserInfo', 'logout']),
    init() {
      this.form = {
        realname: this.userInfo.realname,
        avatar: this.userInfo.avatar || ''
      }
    },
    // 微信头像获取
    onChooseAvatar(e) {
      const {avatarUrl} = e.detail
      const _this = this
      uni.showLoading({
        title: '上传中'
      })
      upload(avatarUrl).then(res => {
        _this.form.avatar = res
        uni.hideLoading()
        _this.submit({
          avatar: res
        })
      }).catch(err => {
      })
    },
    handleTouchInput() {
      let _this = this;
      wx.getPrivacySetting({
        success: res => {
          _this.focus = false
          if (res.needAuthorization) {
            _this.$bus.$on('privacyResult', (data) => {
              _this.focus = data == 'agree'
            })
            _this.$bus.$emit('openPrivacy')
          } else {
            this.$nextTick(() => {
              _this.focus = true
            })
          }
        }
      })
    },
    changeInput(e) {
      this.form.realname = e.detail.value
    },
    updateNickname() {
      this.submit({
        realname: this.form.realname
      })
    },
    onGetPhoneNumber(e) {
      console.log(e)
      if (e.detail.errMsg.indexOf('getPhoneNumber:fail') > -1) {
        this.$toast('获取手机号失败')
        return
      }
      uni.login({
        success: ({code}) => {
          uni.showLoading()
          getSessionKey({code}).then(({sessionId, openid}) => {
            getPhone({
              code: e.detail.code,
              sessionId: sessionId,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv
            }).then(res => {
              updateUserPhone({phone: res.phoneNumber}).then(() => {
                let userInfo = Object.assign({}, this.userInfo)
                userInfo = {
                  ...userInfo,
                 phone: res.phoneNumber
                }
                this.setUserInfo(userInfo);
                this.init()
                this.$toast('修改成功')
              })
            })
          })
        }
      })
    },
    submit(data) {
      let params = {
        realname: this.userInfo.realname,
        avatarUrl: this.userInfo.avatar || '',
        ...data
      }
      updateUserInfo(params).then(res => {
        this.showNicknamePopup = false
        let userInfo = Object.assign({}, this.userInfo)
        userInfo = {
          ...userInfo,
         ...params
        }
        this.setUserInfo(userInfo);
        this.init()
        this.$toast('修改成功')
      })
    },
    toEditPassword() {
      uni.navigateTo({
        url: '/pages/my/setting/edit-password'
      })
    },
    handleLogout() {
      miniLogout().then(() => {
        this.logout()
      })
    }
  },
  onShow() {
    this.init()
  }
}
</script>

<style lang="scss">
@import "@/static/styles/minix.scss";
page {
  background: #fff;
}
.setting-container {
  .cell-group {
    padding: 0 30rpx;
    .cell {
      @include flex-between;
      padding: 30rpx 0;
      border-bottom: 1px solid #f4f4f4;
      .iconfont {
        color: $-color-muted;
      }
      input {
        flex: 1;
        text-align: right;
      }
      button {
        display: flex;
      }
      .avatar-img {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
      }
      .cell-right {
        display: flex;
        align-items: center;
        .unphone {
          font-size: 24rpx;
        }
        .iconfont {
          font-size: 24rpx;
        }
      }
    }
    .logout-btn {
      width: 100%;
      height: 90rpx;
      line-height: 90rpx;
      font-size: 32rpx;
      color: #fff;
      background: #000;
      border-radius: 16rpx;
      margin-top: 70rpx;
    }
  }
  .nick-input {
    height: 90rpx;
    border: 1rpx solid #f4f4f4;
    padding: 0 30rpx;
    border-radius: 16rpx;
    margin-bottom: 60rpx;
    input {
      width: 100%;
      height: 100%;
      line-height: 90rpx;
    }
  }
}
</style>
